/*
	Copyright (C) 2013 Pontificia Universidad Catolica del Peru
	contact: http://avatar.inf.pucp.edu.pe/realidad-aumentada/
	address contact: Av. Universitaria 1801, San Miguel, Lima-Peru.
	
	This file is part of UbicAR PUCP.

	This program is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with This program.  If not, see <http://www.gnu.org/licenses/>.
*/
/*
	Authors: Alvaro Roger Agüero Sánchez, Rodolfo Javier Galvez Meza
	Pontificia Universidad Catolica del Peru
	Departamento de Ingeniería
*/

package org.grupoavatar.guiaubicua.punto;

import java.io.IOException;
import java.io.UnsupportedEncodingException;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.grupoavatar.guiaubicua.R;
import org.grupoavatar.guiaubicua.auxiliares.Interaccion;
import org.grupoavatar.guiaubicua.auxiliares.InteraccionEmail;
import org.grupoavatar.guiaubicua.auxiliares.InteraccionWeb;
import org.grupoavatar.guiaubicua.auxiliares.Servicio;
import org.grupoavatar.guiaubicua.auxiliares.Utiles;
import org.grupoavatar.guiaubicua.mix.data.Json;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class TabServicios extends MasterActivity {

	private ServicioAdapter adapter;
	private ListView lstServicios;
	public static TabServicios context;
	private static ProgressDialog pd;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		context = this;
		if (marker.getServicios() == null || marker.getServicios().size()==0) {
			setContentView(R.layout.no_servicios);
			
		} else {
			setContentView(R.layout.tab_servicios);		
			
			Lugar lugar = new Lugar(marker);
			
			adapter = new ServicioAdapter(this, lugar.getServicios());
			
			lstServicios = (ListView)findViewById(R.id.lstServicios);
			lstServicios.setAdapter(adapter);
			
			lstServicios.setOnItemClickListener(new OnItemClickListener() {
				@Override
				public void onItemClick(AdapterView<?> l, View v, int position, long id) {
					final Servicio serv = marker.getServicios().get(position);
					if (TabServicios.context != null) {
						Dialog dialogPF = new Dialog(TabServicios.context);
						dialogPF.requestWindowFeature(Window.FEATURE_NO_TITLE);
						dialogPF.setContentView(R.layout.detalle_servicios);
						
						ImageView img = (ImageView)dialogPF.findViewById(R.id.img_icono);
						TextView txtTitulo = (TextView)dialogPF.findViewById(R.id.txt_titulo_servicio);
						TextView txtDetalle = (TextView)dialogPF.findViewById(R.id.txt_detalle_servicio);
						Button btnInteraccion = (Button)dialogPF.findViewById(R.id.btnInteraccion);
						btnInteraccion.setOnClickListener(new View.OnClickListener() {
							@Override
							public void onClick(View v) {
								cargarInteraccion(serv, context);
							}
						});
						
						if (serv != null) {
							img.setImageResource(serv.getIcono());
							txtTitulo.setText(serv.getNombre());
							txtDetalle.setText(serv.getDetalle());
							
							if (serv.getIdInteraccion() > 0) {
								btnInteraccion.setText("Interactuar");
								btnInteraccion.setVisibility(View.VISIBLE);
//								switch(serv.getTipoInteraccion()) {
//									case Interaccion.WEB:		btnInteraccion.setText(Interaccion.TEXTO_BOTON_WEB);
//																btnInteraccion.setVisibility(View.VISIBLE);
//																break;
//										
//									case Interaccion.EMAIL:		btnInteraccion.setText(Interaccion.TEXTO_BOTON_EMAIL);
//																btnInteraccion.setVisibility(View.VISIBLE);
//																break;
//																
//									case Interaccion.PRODUCTO:	btnInteraccion.setText(Interaccion.TEXTO_BOTON_PRODUCTO);
//																btnInteraccion.setVisibility(View.GONE);
//																break;
//																
//									default:					btnInteraccion.setVisibility(View.GONE);
//																break;
//								}
							} else {
								btnInteraccion.setVisibility(View.GONE);
							}
							
							dialogPF.show();
						}
					}
				}
			});
		}
		
		btnServicios.setSelected(true);
		btnServicios.setClickable(false);
		context = this;
		btnGeneral.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(TabServicios.this, TabGeneral.class);
				pasarDatos();
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}
		});

		btnUbicacion.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent intent = new Intent(TabServicios.this, TabUbicacion.class);
				pasarDatos();
				startActivity(intent);
				overridePendingTransition(0, 0);
				finish();
				overridePendingTransition(0, 0);
			}
		});
		
														
		
		//Cabecera
//				TextView lblNombre = (TextView) findViewById(R.id.lblNombre);
//				lblNombre.setText(poi.getTitle());
//				TextView lblCategoria = (TextView) findViewById(R.id.lblCategoria);
//				lblCategoria.setText(MixContext.getDataSourceName(poi.getDatasource()));
//				
//				ImageView imageCate = (ImageView) this.findViewById(R.id.imgCategoria);
//		        Bitmap bitfile_cate = ((ArpucpPOIMarker)poi).getDataSourceCircleIconRA(this.getResources());                
//		        imageCate.setImageBitmap(bitfile_cate);  
		
	}
	
	protected void onResume() {
		super.onResume();
		context = this;
	}
	
	public void cargarInteraccion(final Servicio servicio, final TabServicios tabServicios) {
		
		pd = new ProgressDialog(TabServicios.context);
		pd.setMessage("Cargando...");
		
		pd.setButton("Cancelar", new DialogInterface.OnClickListener() 
	    {
	        public void onClick(DialogInterface dialog, int which) 
	        {		
	        	return;
	        }
	    });
		
		Thread cargaInteraccion = new Thread()
		{
			@Override
			public void run() {
				Interaccion interaccion = null;
				String resultado = "";
				try {
					resultado = EntityUtils.toString(makeRequest(Utiles.getConsultarInteraccionURL(servicio.getIdInteraccion())).getEntity());
					System.out.println(resultado);
					interaccion = leerJson(resultado, servicio.getIdInteraccion());
					//servicio.setTipoInteraccion(interaccion.getTipo());
				} catch (Exception e) {
					e.printStackTrace();
				} finally {
					try {
						if (pd.isShowing()) {
							pd.dismiss();
							pd = null;
							if (interaccion != null) {
								ejecutarInteraccion(interaccion, tabServicios);
							} else {
								tabServicios.runOnUiThread(new Runnable() {
									public void run() {
										Toast.makeText(TabServicios.context, "No se logró cargar, intente nuevamente.", Toast.LENGTH_SHORT).show();
									}
								});
								
							}
						}
					} catch (Exception e) {
						e.printStackTrace();
						tabServicios.runOnUiThread(new Runnable() {
							public void run() {
								Toast.makeText(TabServicios.context, "No se pudo ejecutar la acción.", Toast.LENGTH_SHORT).show();
							}
						});
					}
				}
			}
			
			public HttpResponse makeRequest(String uri) {
			    try {
			        HttpGet httpGet = new HttpGet(uri);
			        return new DefaultHttpClient().execute(httpGet);
			    } catch (UnsupportedEncodingException e) {
			        e.printStackTrace();
			    } catch (ClientProtocolException e) {
			        e.printStackTrace();
			    } catch (IOException e) {
			        e.printStackTrace();
			    }
			    return null;
			}
		};
		
		pd.show();
		
		cargaInteraccion.start();
	}
	
	public Interaccion leerJson(String json, int id) {
		Interaccion interaccion = null;
		Json layer = new Json();
		JSONObject root;
		try {
			root = new JSONObject(json);
			interaccion = layer.processInteraccion(root, id);
		} catch (JSONException e) {
			e.printStackTrace();
		}
		return interaccion;
	}
	
	public void ejecutarInteraccion(Interaccion interaccion, TabServicios tabServicios) {
		switch(interaccion.getTipo()) {
			case Interaccion.WEB:		InteraccionWeb interaccionWeb = (InteraccionWeb) interaccion;
										Intent intent = new Intent(Intent.ACTION_VIEW);
										Uri data  = Uri.parse(interaccionWeb.getUrl());
							            intent.setData(data);
							            tabServicios.startActivity(intent);
										break;
	
			case Interaccion.EMAIL:		InteraccionEmail interaccionEmail = (InteraccionEmail) interaccion;
										Intent emailIntent = new Intent(android.content.Intent.ACTION_SEND); 
										emailIntent.putExtra(android.content.Intent.EXTRA_EMAIL, new String[] { interaccionEmail.getEmail() });  
										emailIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, interaccionEmail.getSubject());
										emailIntent.putExtra(android.content.Intent.EXTRA_TEXT, interaccionEmail.getMessage());
										emailIntent.setType("plain/text");  
										tabServicios.startActivity(Intent.createChooser(emailIntent, "Enviar correo con:"));
										break;
					
			case Interaccion.PRODUCTO:	break;
			
			default:					break;
		}
		
		  
	}
}
